package com.wlps.handler;

/**
 * <p>
 *
 * </p>
 *
 * @author ZWYZY
 * @since 2020/7/28
 */

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.wlps.contant.Contant;
import com.wlps.result.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 退出登录处理器
 */
@Component
public class CustomerLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse
            response, Authentication authentication) throws IOException, ServletException {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String token = request.getHeader("token");
        if (redisTemplate.hasKey(Contant.TOKEN_KEY + token)) {
            Integer userId = (Integer) redisTemplate.opsForValue().get(Contant.TOKEN_KEY + token);

            redisTemplate.delete(Contant.TOKEN_ID_KEY + userId);
            redisTemplate.delete(Contant.TOKEN_KEY + token);
            redisTemplate.opsForValue().decrement(Contant.ONLINEUSER_KEY);
        }

        if (auth != null) {
            System.out.println("有数据");
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        System.out.println("没数据");
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = response.getOutputStream();
        String res = JSONObject.toJSONString(ResultUtils.success("退出登录成功！"),
                SerializerFeature.DisableCircularReferenceDetect);
        out.write(res.getBytes("UTF-8"));
        out.flush();
        out.close();
    }
}
